using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UserManagement.Models;

namespace UserManagement.Services
{
    public class UserService : IUserService
    {
        private static List<User> _users = new()
        {
            new User { Id = 1, Name = "张三", Email = "zhangsan@example.com", Age = 25 },
            new User { Id = 2, Name = "李四", Email = "lisi@example.com", Age = 30 },
            new User { Id = 3, Name = "王五", Email = "wangwu@example.com", Age = 28 }
        };

        private static int _nextId = 4;

        public Task<List<User>> GetAllUsersAsync()
        {
            return Task.FromResult(_users.ToList());
        }

        public Task<User?> GetUserByIdAsync(int id)
        {
            var user = _users.FirstOrDefault(u => u.Id == id);
            return Task.FromResult(user);
        }

        public Task<bool> AddUserAsync(User user)
        {
            try
            {
                user.Id = _nextId++;
                user.CreateDate = DateTime.Now;
                _users.Add(user);
                return Task.FromResult(true);
            }
            catch
            {
                return Task.FromResult(false);
            }
        }

        public Task<bool> UpdateUserAsync(User user)
        {
            try
            {
                var existingUser = _users.FirstOrDefault(u => u.Id == user.Id);
                if (existingUser != null)
                {
                    existingUser.Name = user.Name;
                    existingUser.Email = user.Email;
                    existingUser.Age = user.Age;
                    existingUser.IsActive = user.IsActive;
                    return Task.FromResult(true);
                }
                return Task.FromResult(false);
            }
            catch
            {
                return Task.FromResult(false);
            }
        }

        public Task<bool> DeleteUserAsync(int id)
        {
            try
            {
                var user = _users.FirstOrDefault(u => u.Id == id);
                if (user != null)
                {
                    _users.Remove(user);
                    return Task.FromResult(true);
                }
                return Task.FromResult(false);
            }
            catch
            {
                return Task.FromResult(false);
            }
        }
    }
}